const express = require("express");
const { ApolloServer, gql } = require("apollo-server-express");
// const { ApolloServer, gql } = require("apollo-server");

const app = express();

const books = [
  {
    title: "The Awakening",
    author: "Kate Chopin",
  },
  {
    title: "City of Glass",
    author: "Paul Auster",
  },
];

const users = [
  {
    id: "1",
    name: "Alice",
  },
  {
    id: "2",
    name: "Bob",
  },
];

const typeDefs = gql`
  type User {
    id: ID!
    name: String!
  }

  type Book {
    title: String
    author: String
  }
  type Query {
    books: [Book]
    nubmerSxi: Int!
    numberSeven: Int!
    user(id: ID!): User
  }
`;

const resolvers = {
  // 所有的 Query 都走这里
  Query: {
    books: () => books,
    nubmerSxi: () => 6,
    numberSeven: () => 7,
    // args 就是查询参数，比如 user(id: "1")
    user: (parent, args, context, info) => {
      return users.find((user) => user.id === args.id);
    },
  },
};

const server = new ApolloServer({ typeDefs, resolvers });
server.applyMiddleware({ app });

app.use((req, res) => {
  res.status(200);
  res.send("Hello!");
  res.end();
});

app.listen(4000, () => {
  console.log(
    `Server is running on http://localhost:4000${server.graphqlPath}`
  );
});
